/** @param {import('pixi.js').Application} app  */
export function useDrag({
  app,
  calcStartPoint = R.prop('global'),
  elem,
  pred = R.T,
}) {
  const listenerMap = {
    /** 定制 pointermove 触发调用的函数 */
    moveListener: R.identity,
    pointerup: R.identity,
    pointermove: R.identity,
    data: null,
  };

  elem.on(
    'pointerdown',
    R.both(
      pred,
      event => {
        const startPoint = calcStartPoint(event);
        listenerMap.pointerdown({ event, startPoint });

        const handlePointerMove = event => {
          listenerMap.pointermove({ event, startPoint });
        };

        app.stage.on('pointermove', handlePointerMove);

        // pointerleave 就取消监听 pointerup
        const handlePointerLeave = () => {
          handleEnd();
          app.stage.off('pointerup', handlePointerUp);
        };

        // pointerup 就取消监听 pointerleave
        const handlePointerUp = () => {
          handleEnd();
          app.stage.off('pointerleave', handlePointerLeave);
        };

        // pointerup 和 pointerleave 最终都取消监听 pointermove

        app.stage.once('pointerleave', handlePointerLeave);
        app.stage.once('pointerup', handlePointerUp);

        function handleEnd() {
          listenerMap.pointerup();
          listenerMap.data = null;
          app.stage.off('pointermove', handlePointerMove);
        }
      }
    )
  );

  return listenerMap;
}
